const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const _ = db.command

exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const { action, data } = event
  
  console.log('业务管理云函数调用:', { action, openid: wxContext.OPENID })
  
  try {
    switch (action) {
      // 订单管理
      case 'createOrder':
        return await createOrder(wxContext, data)
      case 'getOrders':
        return await getOrders(wxContext, data)
      case 'getUserOrders':
        return await getUserOrders(wxContext, data)
      case 'updateOrderStatus':
        return await updateOrderStatus(wxContext, data)
      case 'getOrderDetail':
        return await getOrderDetail(wxContext, data)
      case 'getOrderHistory':
        return await getOrderHistory(wxContext, data)
      
      // 项目管理
      case 'createProject':
        return await createProject(wxContext, data)
      case 'getProjects':
        return await getProjects(wxContext, data)
      case 'updateProject':
        return await updateProject(wxContext, data)
      case 'getProjectDetail':
        return await getProjectDetail(wxContext, data)
      
      // 服务管理
      case 'getServices':
        return await getServices()
      case 'bookService':
        return await bookService(wxContext, data)
      
      // 统计数据
      case 'getStats':
        return await getStats(wxContext)

      // 批量创建服务项目
      case 'batchCreateServices':
        return await batchCreateServices(wxContext, data)

      // 修复订单serviceId关联
      case 'fixOrderServiceId':
        return await fixOrderServiceId(wxContext, data)

      // 提交客服留言
      case 'submitMessage':
        return await submitMessage(wxContext, data)

      // 记录客服咨询
      case 'logCustomerService':
        return await logCustomerService(wxContext, data)

      // 取消订单
      case 'cancelOrder':
        return await cancelOrder(wxContext, data)

      // 申请取消订单
      case 'requestCancelOrder':
        return await requestCancelOrder(wxContext, data)

      // 处理取消申请
      case 'processCancelRequest':
        return await processCancelRequest(wxContext, data)

      default:
        return {
          success: false,
          error: '未知的操作类型'
        }
    }
  } catch (error) {
    console.error('业务管理云函数错误:', error)
    return {
      success: false,
      error: error.message
    }
  }
}

// 创建订单 - 优化版本（支持服务外键）
async function createOrder(wxContext, orderData) {
  const openid = wxContext.OPENID
  const currentTime = new Date()
  
  console.log('📝 开始创建订单')
  console.log('用户openid:', openid)
  console.log('订单数据:', JSON.stringify(orderData, null, 2))
  
  // 数据验证
  if (!orderData.customerName || !orderData.phone) {
    throw new Error('必填字段缺失：客户姓名和电话不能为空')
  }
  
  // 验证服务信息（支持新旧两种方式）
  if (!orderData.serviceId && !orderData.serviceType) {
    throw new Error('必须指定服务信息：serviceId 或 serviceType')
  }
  
  // 获取用户信息
  let userInfo = null
  try {
    const userQuery = await db.collection('users').where({
      openid: openid
    }).get()
    
    if (userQuery.data.length > 0) {
      userInfo = userQuery.data[0]
      console.log('👤 获取到用户信息:', userInfo.nickName || '未知用户')
    } else {
      console.log('⚠️ 未找到用户信息，将创建新用户记录')
    }
  } catch (error) {
    console.warn('获取用户信息失败:', error.message)
  }
  
  // 获取服务信息（如果提供了serviceId）
  let serviceInfo = null
  console.log('🔍 检查serviceId:', orderData.serviceId)
  console.log('🔍 serviceId类型:', typeof orderData.serviceId)
  console.log('🔍 serviceId长度:', orderData.serviceId ? orderData.serviceId.length : 'N/A')

  if (orderData.serviceId) {
    try {
      // 验证serviceId格式
      if (typeof orderData.serviceId === 'string' && orderData.serviceId.length === 24) {
        console.log('✅ serviceId格式验证通过（24位MongoDB ObjectId）')
      } else {
        console.warn('⚠️ serviceId格式异常，但仍尝试查询:', orderData.serviceId)
      }

      console.log('🔗 尝试通过_id字段获取服务信息，serviceId:', orderData.serviceId)
      const serviceResult = await db.collection('services').doc(orderData.serviceId).get()
      if (serviceResult.data) {
        serviceInfo = serviceResult.data
        console.log('✅ 通过_id字段关联服务信息成功:', serviceInfo.title)
        console.log('🔗 确认服务数据库_id:', serviceInfo._id)
        console.log('🔗 serviceId匹配:', orderData.serviceId === serviceInfo._id)
      } else {
        console.log('⚠️ 通过_id字段未找到服务信息，serviceId:', orderData.serviceId)
      }
    } catch (error) {
      console.warn('❌ 通过_id字段获取服务信息失败:', error.message)
      console.warn('serviceId:', orderData.serviceId)
      console.warn('错误详情:', error)
    }
  } else {
    console.log('⚠️ 未提供serviceId，跳过服务关联')
  }
  
  // 生成订单ID
  const timestamp = Date.now()
  const random = Math.random().toString(36).substr(2, 4).toUpperCase()
  const orderId = `ORD${timestamp}${random}`
  
  // 构建订单对象
  const order = {
    id: orderId,
    openid: openid,
    userId: userInfo?.userId || null,
    userDisplayId: userInfo?.displayId || null,
    customerName: orderData.customerName.trim(),
    phone: orderData.phone.trim(),
    company: orderData.company?.trim() || '',
    
    // === 服务关联字段（新） ===
    serviceId: orderData.serviceId || null,
    serviceCategoryCode: serviceInfo?.category || orderData.serviceType || null,
    
    // === 兼容字段（保留） ===
    serviceType: serviceInfo?.category || orderData.serviceType || '',
    serviceTypeLabel: serviceInfo?.title || orderData.serviceTypeLabel || '',
    
    serviceProject: orderData.serviceProject?.trim() || '',
    description: orderData.description?.trim() || '',
    preferredDate: orderData.preferredDate || '',
    preferredTime: orderData.preferredTime || '',
    address: orderData.address?.trim() || '',
    urgency: orderData.urgency || 'normal',
    status: 'pending',
    createTime: currentTime,
    updateTime: currentTime,
    statusHistory: [{
      status: 'pending',
      timestamp: currentTime,
      note: '订单创建'
    }]
  }
  
  console.log('📋 准备插入订单:', orderId)
  
  try {
    // 尝试写入订单数据
    const orderResult = await db.collection('orders').add({
      data: order
    })
    
    console.log('✅ 订单创建成功!')
    console.log('数据库_id:', orderResult._id)
    console.log('🔗 保存的serviceId:', order.serviceId)
    console.log('📋 完整订单数据:', order)
    
    // 创建对应的项目记录
    try {
      const project = await createProjectFromOrder(order)
      console.log('✅ 项目记录创建成功:', project.id)
    } catch (projectError) {
      console.error('❌ 项目记录创建失败:', projectError.message)
      // 项目创建失败不影响订单创建成功
    }
    
    return {
      success: true,
      orderId: orderId,
      data: order,
      message: '订单创建成功'
    }
    
  } catch (dbError) {
    console.error('❌ 数据库写入失败!')
    console.error('错误代码:', dbError.errCode)
    console.error('错误信息:', dbError.errMsg)
    console.error('完整错误:', dbError)
    
    // 根据错误代码返回更友好的错误信息
    let errorMessage = '数据库写入失败'
    if (dbError.errCode === -502005) {
      errorMessage = '数据库权限不足，请联系管理员检查orders集合权限设置'
    } else if (dbError.errCode === -502001) {
      errorMessage = '数据格式错误，请检查输入数据'
    } else {
      errorMessage = `数据库错误: ${dbError.errMsg || dbError.message || '未知错误'}`
    }
    
    throw new Error(errorMessage)
  }
}

// 从订单创建项目
async function createProjectFromOrder(order) {
  const projectId = 'PRJ' + order.id.substring(3)
  
  const project = {
    id: projectId,
    orderId: order.id,
    openid: order.openid,
    userId: order.userId, // 关联用户ID
    userDisplayId: order.userDisplayId, // 关联用户显示ID
    name: `${order.customerName} - ${order.serviceTypeLabel || order.serviceType}`,
    description: order.description,
    clientName: order.customerName,
    clientPhone: order.phone,
    clientCompany: order.company,
    serviceType: order.serviceType,
    status: 'planning', // 规划中
    progress: 5,
    startDate: order.createTime,
    createTime: order.createTime,
    updateTime: order.createTime,
    milestones: [
      { name: '需求确认', status: 'pending', progress: 0 },
      { name: '现场查勘', status: 'pending', progress: 0 },
      { name: '方案设计', status: 'pending', progress: 0 },
      { name: '报价确认', status: 'pending', progress: 0 },
      { name: '项目实施', status: 'pending', progress: 0 },
      { name: '质量验收', status: 'pending', progress: 0 },
      { name: '项目交付', status: 'pending', progress: 0 },
      { name: '售后服务', status: 'pending', progress: 0 }
    ]
  }
  
  await db.collection('projects').add({
    data: project
  })
  
  return project
}

// 获取订单列表
async function getOrders(wxContext, params) {
  const openid = wxContext.OPENID
  const { status, limit = 20, skip = 0 } = params || {}
  
  let query = db.collection('orders').where({
    openid: openid
  })
  
  if (status && status !== 'all') {
    if (status === 'in_progress') {
      // 进行中包含多个状态
      query = query.where({
        status: _.in(['confirmed', 'surveying', 'designing', 'quoted', 'in_progress', 'testing'])
      })
    } else {
      query = query.where({
        status: status
      })
    }
  }
  
  const result = await query
    .orderBy('createTime', 'desc')
    .limit(limit)
    .skip(skip)
    .get()
  
  return {
    success: true,
    data: result.data,
    total: result.data.length
  }
}

// 获取用户订单列表
async function getUserOrders(wxContext, params) {
  const openid = wxContext.OPENID
  const { status, limit = 20, skip = 0 } = params || {}
  
  console.log('📋 获取用户订单列表，openid:', openid)
  console.log('筛选条件:', { status, limit, skip })
  
  let query = db.collection('orders').where({
    openid: openid
  })
  
  if (status && status !== 'all') {
    if (status === 'team_accepted') {
      // "已接单"标签包含accepted、team_accepted和confirmed状态
      query = query.where({
        status: db.command.in(['accepted', 'team_accepted', 'confirmed'])
      })
    } else if (status === 'waiting_team') {
      // "等待接单"标签包含pending和waiting_team状态
      query = query.where({
        status: db.command.in(['pending', 'waiting_team'])
      })
    } else {
      // 其他状态直接按状态筛选
      query = query.where({
        status: status
      })
    }
  }
  
  const result = await query
    .orderBy('createTime', 'desc')
    .limit(limit)
    .skip(skip)
    .get()
  
  console.log(`✅ 获取到 ${result.data.length} 个订单`)
  
  return {
    success: true,
    data: result.data,
    total: result.data.length
  }
}

// 更新订单状态
async function updateOrderStatus(wxContext, params) {
  const { orderId, status, note } = params
  const currentTime = new Date()
  
  // 获取当前订单
  const orderQuery = await db.collection('orders').where({
    id: orderId,
    openid: wxContext.OPENID
  }).get()
  
  if (orderQuery.data.length === 0) {
    return {
      success: false,
      error: '订单不存在'
    }
  }
  
  const order = orderQuery.data[0]
  const statusHistory = order.statusHistory || []
  statusHistory.push({
    status: status,
    timestamp: currentTime,
    note: note || ''
  })
  
  // 更新订单状态
  await db.collection('orders').doc(order._id).update({
    data: {
      status: status,
      updateTime: currentTime,
      statusHistory: statusHistory
    }
  })
  
  // 同步更新项目状态
  await updateProjectFromOrder(orderId, status)
  
  return {
    success: true,
    message: '状态更新成功'
  }
}

// 根据订单状态更新项目
async function updateProjectFromOrder(orderId, orderStatus) {
  const projectQuery = await db.collection('projects').where({
    orderId: orderId
  }).get()
  
  if (projectQuery.data.length === 0) {
    return
  }
  
  const project = projectQuery.data[0]
  let projectStatus = project.status
  let progress = project.progress
  let milestones = project.milestones || []
  
  // 根据订单状态更新项目状态和进度
  switch (orderStatus) {
    case 'confirmed':
      projectStatus = 'active'
      progress = 15
      milestones[0] = { ...milestones[0], status: 'completed', progress: 100 }
      break
    case 'surveying':
      projectStatus = 'active'
      progress = 25
      milestones[1] = { ...milestones[1], status: 'in_progress', progress: 50 }
      break
    case 'designing':
      projectStatus = 'active'
      progress = 40
      milestones[1] = { ...milestones[1], status: 'completed', progress: 100 }
      milestones[2] = { ...milestones[2], status: 'in_progress', progress: 50 }
      break
    case 'quoted':
      projectStatus = 'active'
      progress = 55
      milestones[2] = { ...milestones[2], status: 'completed', progress: 100 }
      milestones[3] = { ...milestones[3], status: 'in_progress', progress: 50 }
      break
    case 'in_progress':
      projectStatus = 'active'
      progress = 75
      milestones[3] = { ...milestones[3], status: 'completed', progress: 100 }
      milestones[4] = { ...milestones[4], status: 'in_progress', progress: 50 }
      break
    case 'testing':
      projectStatus = 'testing'
      progress = 90
      milestones[4] = { ...milestones[4], status: 'completed', progress: 100 }
      milestones[5] = { ...milestones[5], status: 'in_progress', progress: 50 }
      break
    case 'completed':
      projectStatus = 'completed'
      progress = 100
      milestones = milestones.map(m => ({ ...m, status: 'completed', progress: 100 }))
      break
  }
  
  await db.collection('projects').doc(project._id).update({
    data: {
      status: projectStatus,
      progress: progress,
      milestones: milestones,
      updateTime: new Date()
    }
  })
}

// 获取订单详情（支持服务外键关联）
async function getOrderDetail(wxContext, params) {
  const { orderId } = params
  
  const result = await db.collection('orders').where({
    id: orderId,
    openid: wxContext.OPENID
  }).get()
  
  if (result.data.length === 0) {
    return {
      success: false,
      error: '订单不存在'
    }
  }
  
  const order = result.data[0]
  
  // 通过外键获取完整服务信息
  let serviceInfo = null
  console.log('🔍 开始查询服务信息，serviceId:', order.serviceId)

  if (order.serviceId) {
    try {
      console.log('📋 尝试查询services集合，serviceId:', order.serviceId)
      const serviceResult = await db.collection('services').doc(order.serviceId).get()
      console.log('📋 服务查询结果:', serviceResult)

      if (serviceResult.data) {
        serviceInfo = serviceResult.data
        console.log('🔗 获取关联服务信息:', serviceInfo.title)
        console.log('🖼️ 服务图片URL:', serviceInfo.image)
        console.log('📋 完整服务信息:', serviceInfo)
      } else {
        console.log('⚠️ 服务查询结果为空')
      }
    } catch (error) {
      console.warn('❌ 获取服务信息失败:', error.message)
      console.warn('错误详情:', error)

      // 尝试通过where查询（如果serviceId不是标准的ObjectId）
      try {
        console.log('🔄 尝试通过where查询服务信息...')
        const whereResult = await db.collection('services').where({
          id: order.serviceId
        }).get()

        if (whereResult.data && whereResult.data.length > 0) {
          serviceInfo = whereResult.data[0]
          console.log('✅ 通过where查询获取服务信息成功:', serviceInfo.title)
        } else {
          console.log('⚠️ where查询也没有找到服务信息')
        }
      } catch (whereError) {
        console.warn('❌ where查询也失败:', whereError.message)
      }
    }
  } else {
    console.log('⚠️ 订单没有serviceId，跳过服务信息查询')
  }
  
  // 兼容旧数据：通过分类代码获取分类信息
  let categoryInfo = null
  if (!serviceInfo && (order.serviceCategoryCode || order.serviceType)) {
    try {
      const categoryCode = order.serviceCategoryCode || order.serviceType
      const categoryResult = await db.collection('service_categories').where({
        code: categoryCode
      }).get()
      
      if (categoryResult.data.length > 0) {
        categoryInfo = categoryResult.data[0]
        console.log('📂 获取分类信息:', categoryInfo.name)
      }
    } catch (error) {
      console.warn('获取分类信息失败:', error.message)
    }
  }
  
  // 查找关联的项目
  let project = null
  try {
    const projectResult = await db.collection('projects').where({
      orderId: orderId
    }).get()
    
    if (projectResult.data.length > 0) {
      project = projectResult.data[0]
    }
  } catch (error) {
    console.warn('获取关联项目失败:', error.message)
  }
  
  return {
    success: true,
    data: {
      ...order,
      serviceInfo: serviceInfo,      // 完整服务信息
      categoryInfo: categoryInfo,    // 分类信息（兼容）
      project: project
    }
  }
}

// 获取订单操作历史
async function getOrderHistory(wxContext, params) {
  const { orderId } = params
  
  // 先验证订单是否存在且属于当前用户
  const orderResult = await db.collection('orders').where({
    id: orderId,
    openid: wxContext.OPENID
  }).get()
  
  if (orderResult.data.length === 0) {
    return {
      success: false,
      error: '订单不存在'
    }
  }
  
  const order = orderResult.data[0]
  
  // 从订单的 statusHistory 字段获取历史记录
  const history = order.statusHistory || []
  
  // 格式化历史记录，添加更友好的动作描述
  const formattedHistory = history.map((item, index) => {
    let action = ''
    switch (item.status) {
      case 'pending':
        action = '订单创建'
        break
      case 'confirmed':
        action = '确认订单'
        break
      case 'surveying':
        action = '开始查勘'
        break
      case 'designing':
        action = '开始设计'
        break
      case 'quoted':
        action = '完成报价'
        break
      case 'in_progress':
        action = '开始施工'
        break
      case 'testing':
        action = '开始验收'
        break
      case 'completed':
        action = '订单完成'
        break
      case 'cancelled':
        action = '订单取消'
        break
      default:
        action = `状态更新为: ${item.status}`
    }
    
    return {
      id: `history_${index}`,
      action: action,
      status: item.status,
      createTime: item.timestamp,
      note: item.note || '',
      operator: item.operator || '系统'
    }
  })
  
  // 按时间倒序排列（最新的在前面）
  formattedHistory.sort((a, b) => new Date(b.createTime) - new Date(a.createTime))
  
  return {
    success: true,
    data: formattedHistory
  }
}

// 获取项目列表
async function getProjects(wxContext, params) {
  const openid = wxContext.OPENID
  const { status, limit = 20, skip = 0 } = params || {}
  
  let query = db.collection('projects').where({
    openid: openid
  })
  
  if (status && status !== 'all') {
    query = query.where({
      status: status
    })
  }
  
  const result = await query
    .orderBy('createTime', 'desc')
    .limit(limit)
    .skip(skip)
    .get()
  
  return {
    success: true,
    data: result.data,
    total: result.data.length
  }
}

// 获取项目详情
async function getProjectDetail(wxContext, params) {
  const { projectId } = params
  
  const result = await db.collection('projects').where({
    id: projectId,
    openid: wxContext.OPENID
  }).get()
  
  if (result.data.length === 0) {
    return {
      success: false,
      error: '项目不存在'
    }
  }
  
  return {
    success: true,
    data: result.data[0]
  }
}

// 获取统计数据
async function getStats(wxContext) {
  const openid = wxContext.OPENID
  console.log('📊 开始统计用户数据，openid:', openid)

  try {
    // 获取订单统计
    const ordersResult = await db.collection('orders').where({
      openid: openid
    }).get()

    // 获取项目统计
    const projectsResult = await db.collection('projects').where({
      openid: openid
    }).get()

    const orders = ordersResult.data
    const projects = projectsResult.data

    console.log(`📋 找到 ${orders.length} 个订单，${projects.length} 个项目`)

    // 统计订单状态分布
    const orderStatusCount = {}
    orders.forEach(order => {
      orderStatusCount[order.status] = (orderStatusCount[order.status] || 0) + 1
    })
    console.log('📊 订单状态分布:', orderStatusCount)

    // 统计项目状态分布
    const projectStatusCount = {}
    projects.forEach(project => {
      projectStatusCount[project.status] = (projectStatusCount[project.status] || 0) + 1
    })
    console.log('📊 项目状态分布:', projectStatusCount)

    const stats = {
      totalOrders: orders.length,
      pendingOrders: orders.filter(o => o.status === 'pending').length,
      activeOrders: orders.filter(o => ['confirmed', 'surveying', 'designing', 'quoted', 'in_progress', 'testing'].includes(o.status)).length,
      completedOrders: orders.filter(o => o.status === 'completed').length,

      totalProjects: projects.length,
      activeProjects: projects.filter(p => ['planning', 'active'].includes(p.status)).length,
      completedProjects: projects.filter(p => p.status === 'completed').length,

      completionRate: orders.length > 0 ? Math.round((orders.filter(o => o.status === 'completed').length / orders.length) * 100) : 0
    }

    console.log('📊 最终统计结果:', stats)

    return {
      success: true,
      data: stats
    }
  } catch (error) {
    console.error('❌ 统计数据失败:', error)
    return {
      success: false,
      error: error.message
    }
  }
}

// 批量创建服务项目
async function batchCreateServices(wxContext, params) {
  const { services } = params

  if (!services || !Array.isArray(services) || services.length === 0) {
    return {
      success: false,
      error: '服务数据不能为空'
    }
  }

  console.log(`🔄 开始批量创建 ${services.length} 项服务...`)

  try {
    const currentTime = new Date()
    const createdServices = []

    // 逐个创建服务项目
    for (let i = 0; i < services.length; i++) {
      const service = services[i]

      // 构建完整的服务对象
      const serviceData = {
        title: service.title,
        description: service.description,
        category: service.category,
        price: service.price || 0,
        unit: service.unit || '',
        rating: service.rating || '4.5',
        badge: service.badge || '',
        tags: service.tags || [],
        image: service.image || '',
        features: service.features || [],
        serviceProcess: service.serviceProcess || [],
        status: 'active',
        createTime: currentTime,
        updateTime: currentTime,
        createdBy: wxContext.OPENID || 'system'
      }

      // 插入到数据库
      const result = await db.collection('services').add({
        data: serviceData
      })

      console.log(`✅ 服务 "${service.title}" 创建成功，ID: ${result._id}`)

      createdServices.push({
        ...serviceData,
        _id: result._id
      })
    }

    console.log(`🎉 批量创建完成，共创建 ${createdServices.length} 项服务`)

    return {
      success: true,
      data: createdServices,
      message: `成功创建 ${createdServices.length} 项服务`
    }

  } catch (error) {
    console.error('❌ 批量创建服务失败:', error)
    return {
      success: false,
      error: `批量创建失败: ${error.message}`
    }
  }
}

// 修复订单serviceId关联
async function fixOrderServiceId(wxContext, params) {
  console.log('🔧 开始修复订单serviceId关联...')

  try {
    // 1. 获取所有services数据，建立映射关系
    const servicesResult = await db.collection('services').get()
    const services = servicesResult.data

    console.log(`📋 获取到 ${services.length} 个服务项目`)

    // 建立服务标题到_id的映射
    const serviceMapping = {}
    services.forEach(service => {
      // 通过标题映射
      if (service.title) {
        serviceMapping[service.title] = service._id
      }
      // 通过旧的id字段映射（如果存在）
      if (service.id && service.id !== service._id) {
        serviceMapping[service.id] = service._id
      }
    })

    console.log('🗺️ 服务映射关系:', serviceMapping)

    // 2. 获取所有需要修复的订单
    const ordersResult = await db.collection('orders').get()
    const orders = ordersResult.data

    console.log(`📋 获取到 ${orders.length} 个订单`)

    let fixedCount = 0
    const fixResults = []

    // 3. 逐个检查和修复订单
    for (const order of orders) {
      let needUpdate = false
      let newServiceId = null

      console.log(`🔍 检查订单 ${order.id}:`)
      console.log(`  - 当前serviceId: ${order.serviceId}`)
      console.log(`  - serviceProject: ${order.serviceProject}`)

      // 检查当前serviceId是否有效
      if (order.serviceId) {
        try {
          const checkResult = await db.collection('services').doc(order.serviceId).get()
          if (checkResult.data) {
            console.log(`  ✅ serviceId有效，无需修复`)
            continue
          }
        } catch (error) {
          console.log(`  ❌ serviceId无效: ${error.message}`)
        }
      }

      // 尝试通过serviceProject匹配
      if (order.serviceProject && serviceMapping[order.serviceProject]) {
        newServiceId = serviceMapping[order.serviceProject]
        needUpdate = true
        console.log(`  🔗 通过serviceProject匹配到: ${newServiceId}`)
      }
      // 尝试通过旧的serviceId匹配
      else if (order.serviceId && serviceMapping[order.serviceId]) {
        newServiceId = serviceMapping[order.serviceId]
        needUpdate = true
        console.log(`  🔗 通过旧serviceId匹配到: ${newServiceId}`)
      }
      // 根据服务类型进行智能匹配
      else if (order.serviceType) {
        const matchedService = services.find(service =>
          service.category === order.serviceType ||
          service.serviceType === order.serviceType
        )
        if (matchedService) {
          newServiceId = matchedService._id
          needUpdate = true
          console.log(`  🔗 通过serviceType匹配到: ${newServiceId} (${matchedService.title})`)
        }
      }

      // 执行更新
      if (needUpdate && newServiceId) {
        try {
          await db.collection('orders').doc(order._id).update({
            data: {
              serviceId: newServiceId,
              updateTime: new Date()
            }
          })

          fixedCount++
          fixResults.push({
            orderId: order.id,
            oldServiceId: order.serviceId,
            newServiceId: newServiceId,
            matchMethod: order.serviceProject ? 'serviceProject' :
                        (order.serviceId && serviceMapping[order.serviceId]) ? 'oldServiceId' : 'serviceType'
          })

          console.log(`  ✅ 订单 ${order.id} 修复成功`)
        } catch (updateError) {
          console.error(`  ❌ 订单 ${order.id} 更新失败:`, updateError.message)
        }
      } else {
        console.log(`  ⚠️ 订单 ${order.id} 无法自动匹配服务`)
      }
    }

    console.log(`🎉 修复完成，共修复 ${fixedCount} 个订单`)

    return {
      success: true,
      message: `serviceId关联修复完成`,
      data: {
        totalOrders: orders.length,
        fixedCount: fixedCount,
        fixResults: fixResults
      }
    }

  } catch (error) {
    console.error('❌ 修复serviceId失败:', error)
    return {
      success: false,
      error: `修复失败: ${error.message}`
    }
  }
}

// 提交客服留言
async function submitMessage(wxContext, params) {
  const { messageData } = params
  const openid = wxContext.OPENID

  console.log('📝 提交客服留言，用户:', openid)

  try {
    // 验证必填字段
    if (!messageData.name || !messageData.phone || !messageData.subject || !messageData.message) {
      return {
        success: false,
        error: '请填写完整的留言信息'
      }
    }

    // 构建留言数据
    const messageRecord = {
      openid: openid,
      name: messageData.name,
      phone: messageData.phone,
      email: messageData.email || '',
      subject: messageData.subject,
      message: messageData.message,
      urgency: messageData.urgency || 'normal',
      status: 'pending', // pending, processing, resolved, closed
      submitTime: new Date(),
      updateTime: new Date(),
      reply: '', // 客服回复
      replyTime: null
    }

    // 保存到数据库
    const result = await db.collection('customer_messages').add({
      data: messageRecord
    })

    console.log('✅ 客服留言保存成功，ID:', result._id)

    // 可以在这里添加通知逻辑，比如发送邮件给客服团队
    // await notifyCustomerService(messageRecord)

    return {
      success: true,
      message: '留言提交成功',
      data: {
        messageId: result._id,
        submitTime: messageRecord.submitTime
      }
    }

  } catch (error) {
    console.error('❌ 提交客服留言失败:', error)
    return {
      success: false,
      error: `提交失败: ${error.message}`
    }
  }
}

// 记录客服咨询
async function logCustomerService(wxContext, params) {
  const { logData } = params
  const openid = wxContext.OPENID

  console.log('📊 记录客服咨询，用户:', openid)

  try {
    // 构建咨询记录
    const serviceLog = {
      openid: openid,
      type: logData.type || 'wechat_chat',
      path: logData.path || '',
      query: logData.query || '',
      timestamp: new Date(),
      userAgent: logData.userAgent || '',
      sessionId: `${openid}_${Date.now()}`
    }

    // 保存到数据库
    const result = await db.collection('customer_service_logs').add({
      data: serviceLog
    })

    console.log('✅ 客服咨询记录保存成功，ID:', result._id)

    return {
      success: true,
      message: '咨询记录保存成功',
      data: {
        logId: result._id,
        timestamp: serviceLog.timestamp
      }
    }

  } catch (error) {
    console.error('❌ 记录客服咨询失败:', error)
    return {
      success: false,
      error: `记录失败: ${error.message}`
    }
  }
}

// 获取服务列表
async function getServices() {
  const services = [
    { 
      id: 1, 
      key: 'sme_market', 
      name: '中小市场', 
      icon: '🏢',
      description: '为中小企业提供市场拓展和商业咨询服务',
      price: '面议'
    },
    { 
      id: 2, 
      key: 'info_integration', 
      name: '信息化集成', 
      icon: '💻',
      description: '企业信息化系统集成，包含ERP、CRM、OA等',
      price: '8800起'
    },
    { 
      id: 3, 
      key: 'engineering', 
      name: '工程施工', 
      icon: '🏗️',
      description: '专业工程项目施工管理，从设计到验收全程跟踪',
      price: '15000起'
    },
    { 
      id: 4, 
      key: 'network_maintenance', 
      name: '网络维护', 
      icon: '🔧',
      description: '专业网络设备巡检维护，7x24小时技术支持',
      price: '2800/月'
    },
    { 
      id: 5, 
      key: 'smart_home', 
      name: '智能家居', 
      icon: '🏠',
      description: '智能家居系统设计安装，包含智能照明、安防等',
      price: '12000起'
    },
    { 
      id: 6, 
      key: 'measurement', 
      name: '计量检测', 
      icon: '📏',
      description: '专业计量设备检测校准，提供权威检测报告',
      price: '800/次'
    },
    { 
      id: 7, 
      key: 'materials', 
      name: '材料设备', 
      icon: '📦',
      description: '优质工程材料和设备采购供应服务',
      price: '面议'
    },
    { 
      id: 8, 
      key: 'construction_team', 
      name: '施工队伍', 
      icon: '👷',
      description: '专业施工队伍派遣和管理服务',
      price: '面议'
    }
  ]
  
  return {
    success: true,
    data: services
  }
}

// 预约服务
async function bookService(wxContext, serviceData) {
  // 直接调用创建订单功能
  return await createOrder(wxContext, serviceData)
}

// 取消订单
async function cancelOrder(wxContext, params) {
  const { orderId, reason, needTeamApproval } = params
  const currentTime = new Date()
  
  console.log('📋 开始取消订单:', { orderId, reason, needTeamApproval })
  
  // 获取当前订单
  const orderQuery = await db.collection('orders').where({
    id: orderId,
    openid: wxContext.OPENID
  }).get()
  
  if (orderQuery.data.length === 0) {
    return {
      success: false,
      error: '订单不存在或无权限操作'
    }
  }
  
  const order = orderQuery.data[0]
  
  // 检查订单状态是否可以取消
  const cancelableStatuses = ['pending', 'confirmed', 'waiting_team', 'surveying', 'designing', 'quoted']
  if (!cancelableStatuses.includes(order.status)) {
    return {
      success: false,
      error: '当前订单状态不允许取消'
    }
  }
  
  // 更新订单状态和取消信息
  const updateData = {
    status: 'cancelled',
    updateTime: currentTime,
    cancelTime: currentTime,
    cancelReason: reason || '用户主动取消',
    cancelBy: wxContext.OPENID
  }
  
  // 添加状态历史记录
  if (order.statusHistory) {
    updateData.statusHistory = _.push([{
      status: 'cancelled',
      timestamp: currentTime,
      note: `订单已取消，原因：${reason || '用户主动取消'}`,
      operator: wxContext.OPENID
    }])
  }
  
  await db.collection('orders').doc(order._id).update({
    data: updateData
  })
  
  // 记录操作历史
  try {
    await db.collection('order_actions').add({
      data: {
        orderId: orderId,
        action: '取消订单',
        note: `取消原因：${reason || '用户主动取消'}`,
        operator: wxContext.OPENID,
        createTime: currentTime
      }
    })
  } catch (error) {
    console.warn('记录操作历史失败:', error.message)
  }
  
  // 同步更新项目状态
  await updateProjectFromOrder(orderId, 'cancelled')
  
  console.log('✅ 订单取消成功:', orderId)
  
  return {
    success: true,
    message: '订单取消成功'
  }
}

// 申请取消订单
async function requestCancelOrder(wxContext, params) {
  const { orderId, reason } = params
  const currentTime = new Date()
  
  console.log('📋 开始申请取消订单:', { orderId, reason })
  
  // 获取当前订单
  const orderQuery = await db.collection('orders').where({
    id: orderId,
    openid: wxContext.OPENID
  }).get()
  
  if (orderQuery.data.length === 0) {
    return {
      success: false,
      error: '订单不存在或无权限操作'
    }
  }
  
  const order = orderQuery.data[0]
  
  // 检查订单是否已被施工队伍接单
  const teamAcceptedStatuses = ['team_accepted', 'team_preparing', 'team_on_site', 'in_progress', 'paused', 'testing']
  if (!teamAcceptedStatuses.includes(order.status)) {
    // 如果还没有被施工队伍接单，直接取消
    return await cancelOrder(wxContext, { orderId, reason, needTeamApproval: false })
  }
  
  // 更新订单状态为申请取消
  const updateData = {
    status: 'cancel_pending',
    updateTime: currentTime,
    cancelRequestTime: currentTime,
    cancelRequestReason: reason || '用户申请取消',
    cancelRequestBy: wxContext.OPENID
  }
  
  // 添加状态历史记录
  if (order.statusHistory) {
    updateData.statusHistory = _.push([{
      status: 'cancel_pending',
      timestamp: currentTime,
      note: `客户申请取消订单，原因：${reason || '用户申请取消'}，等待施工队伍确认`,
      operator: wxContext.OPENID
    }])
  }
  
  await db.collection('orders').doc(order._id).update({
    data: updateData
  })
  
  // 记录操作历史
  try {
    await db.collection('order_actions').add({
      data: {
        orderId: orderId,
        action: '申请取消订单',
        note: `申请原因：${reason || '用户申请取消'}，等待施工队伍确认`,
        operator: wxContext.OPENID,
        createTime: currentTime
      }
    })
  } catch (error) {
    console.warn('记录操作历史失败:', error.message)
  }
  
  // 同步更新项目状态
  await updateProjectFromOrder(orderId, 'cancel_pending')
  
  // TODO: 发送通知给施工队伍
  // 这里可以调用消息推送功能通知施工队伍有取消申请
  
  console.log('✅ 订单取消申请提交成功:', orderId)
  
  return {
    success: true,
    message: '取消申请已提交，等待施工队伍确认'
  }
}

// 处理取消申请
async function processCancelRequest(wxContext, params) {
  const { orderId } = params
  const currentTime = new Date()
  
  // 获取当前订单
  const orderQuery = await db.collection('orders').where({
    id: orderId,
    openid: wxContext.OPENID
  }).get()
  
  if (orderQuery.data.length === 0) {
    return {
      success: false,
      error: '订单不存在'
    }
  }
  
  const order = orderQuery.data[0]
  
  // 更新订单状态为已取消
  await db.collection('orders').doc(order._id).update({
    data: {
      status: 'cancelled',
      updateTime: currentTime
    }
  })
  
  // 同步更新项目状态
  await updateProjectFromOrder(orderId, 'cancelled')
  
  return {
    success: true,
    message: '取消申请处理成功'
  }
} 